<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;

class UserInit extends Command
{
    protected function configure()
    {
        $this->setName('UserInit')->setDescription("计划任务 UserInit");
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('Date Crontab job start...');
        /*** 这里写计划任务列表集 START ***/

        $this->init_path();
        $this->initUserNun();

        /*** 这里写计划任务列表集 END ***/
        $output->writeln('Date Crontab job end...');
    }

    private function initUserNun()
    {
        $lists = \db('share_user')->select();
        if (!empty($lists)) {
            $userModel = new \app\admin\model\share\ShareUser();
            foreach ($lists as $val) {
                $uidArrAll = $userModel->getTeamUser($val['user_id']);
                $uidStr = implode(',', $uidArrAll['team_user']);

                \db('share_user')->where(['user_id' => $val['user_id']])->update(['amount' => count($uidArrAll['team_user']), 'new_amount' => $uidStr]);
            }
        }
        echo date("Y-m-d H:i:s") . " 初始化团队人数处理完成 \r\n";

    }

    private function init_path()
    {
        $list = \db("share_user")->select();
        foreach ($list as $v) {
            echo $v['user_id'] . PHP_EOL;
            $url = $this->add_promotion($v['user_id']);
            $url = str_replace('/' . $v['user_id'], '', $url);
            \db("share_user")->where("user_id", $v['user_id'])->update(['role_url' => $url]);
        }
    }

    private function add_promotion($user_id, $role_url = '')
    {
        $user = \db("share_user")->where('user_id', $user_id)->find();
        if (empty($user)) {
            return $role_url;
        }

        $role_url = $role_url . '/' . $user['user_id'];
        // 最高等级结束
        if ($user['role'] == 7) {
            return $role_url;
        }
        return $this->add_promotion($user['parent_id'], $role_url);
    }


}
